<?php
/**
 * Created by <xinxin.deng>.
 * Author: xinxin.deng
 * Date: 2018/7/30 14:51
 */

//error_reporting(E_ALL);
set_time_limit(0);
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_model.message.message_explain");
\ns_core\m_load::load("ns_core.m_config");
\ns_core\m_load::load("ns_core.m_pinyin");
\ns_core\m_load::load_old("nn_logic/log_model/nn_log.class.php");
\ns_core\m_load::load_old("nn_logic/video/vod_index.class.php");
\ns_core\m_load::load_old("nn_logic/video/vod_media.class.php");
//\ns_core\m_load::load_old("nn_logic/video/vod.class.php");
\ns_core\m_load::load_np("np_http_curl.class.php");
class message extends \ns_model\message\message_explain
{
    private $view_type = array(
        '0' => array('84','112','6','9','32','14','28','31'),//电影
        '1' => array('5','83','34'),//电视剧
        '2' => array('19','87'),//综艺
        '3' => array('20','88'),//动漫
        '4' => array('18','86'),//音乐
        '5' => array('17','85'),//纪实
        '6' => array('22','97'),//教育
        '7' => array('23','98'),//体育
        '8' => array('25','100'),//生活
        '9' => array('24','99'),//财经
        '10' => array('26','101','10'),//微电影
        '11' => array('27','102'),//品牌专区
        '12' => array('21','92','33','113'),//广告
        '13' => array('11','30'),//新闻
    );//影片种类

    private $msg_id = '';
    private $source_id = '';
    private $arr_cp_config = array();

    private $asset_id = '';
    private $index_id = '';
    private $media_id = '';
    private $type = '';

    /**
     * 消息解析
     * @param $message
     * @return array|multitype
     */
    public function explain($message)
    {
        \ns_core\m_load::load_np("np_xml_to_array.class.php");
        $this->type = '';
        $this->asset_id = '';
        $this->index_id = '';
        $this->media_id = '';

        $this->msg_id = $message['nns_message_id'];
        $this->source_id = $message['nns_cp_id'];
        $this->arr_cp_config = \m_config::_get_cp_info($message['nns_cp_id']);
        //本地获取数据
        $content = $this->get_message_content($message);
        if($content['ret'] != 0 || strlen($content['data_info']) < 1)
        {
            $this->create_xml_respond_msg_to_csp(NS_CDS_FAIL, "消息接收成功,注入失败，消息ID[{$message['nns_message_id']}]" . $content['reason']);
            return $content;
        }
        $str_content = \m_config::trim_xml_header($content['data_info']);
        if(!\m_config::is_xml($str_content))
        {
            $this->create_xml_respond_msg_to_csp(NS_CDS_FAIL, "消息接收成功,注入失败,消息ID[{$message['nns_message_id']}]xml内容非xml结构");
            return \m_config::return_data(NS_CDS_FAIL,"消息ID[{$message['nns_message_id']}]xml内容非xml结构");
        }
        //解析下载的XML
        $dom = new DOMDocument('1.0', 'utf-8');
        $dom->loadXML($str_content);
        $xml = $dom->saveXML();
        $xml_arr = np_xml_to_array::parse2($xml);
        if(!is_array($xml_arr) || empty($xml_arr))
        {
            $this->create_xml_respond_msg_to_csp(NS_CDS_FAIL, "消息接收成功,注入失败,消息ID[{$message['nns_message_id']}]xml解析失败");
            return \m_config::return_data(NS_CDS_FAIL,"消息ID[{$message['nns_message_id']}]xml解析失败");
        }

        if(!isset($xml_arr['content']) || empty($xml_arr['content']))
        {
            $this->create_xml_respond_msg_to_csp(NS_CDS_FAIL, "消息接收成功,注入失败,消息ID[{$message['nns_message_id']}],解析得到的媒资元数据错误");
            return \m_config::return_data(1, "解析得到的媒资元数据错误");
        }

        $this->type = (int)$xml_arr['assetdesc'];
        switch ($xml_arr['assettype'])
        {
            case 1 ://点播业务处理
                if ($xml_arr['assetdesc'] == 1) //主媒资
                {
                    //全局消息自带反馈主媒资id
                    $this->asset_id = $xml_arr['content']['assetid'];

                    $re = $this->video_execute($xml_arr);
                }
                elseif ($xml_arr['assetdesc'] == 2) //分集
                {
                    //全局消息自带反馈主媒资id
                    $this->asset_id = $xml_arr['content']['assetid'];
                    //全局消息自带反馈分集id
                    $this->index_id = $xml_arr['content']['partid'];
                    $re = $this->index_execute($xml_arr);
                }
                break;
            default:
                $re = \m_config::return_data(1, "不支持的工单类型");
                break;
        }

        if ($re['ret'] != 0)
        {
            $this->create_xml_respond_msg_to_csp(NS_CDS_FAIL, "消息接收成功,注入失败,消息ID[{$message['nns_message_id']}],原因" . $re['reason']);
        }
        else
        {
            $this->create_xml_respond_msg_to_csp(NS_CDS_SUCCE, "消息接收成功,等待注入,消息ID[{$message['nns_message_id']}]");
        }
        unset($this->type);
        unset($this->asset_id);
        unset($this->index_id);
        unset($this->media_id);
        return $re;
    }

    /**
     * 主媒资队列修改注入
     * @param $data
     * @return array
     */
    private function video_execute($data)
    {
        $content = $data['content'];
        if ($data['assetoperation'] != 1)
        {
            return \m_config::return_data(1, '只接收处理集合或者分集的修改');
        }

        //获取view_type
        $view_type = '0';
        foreach ($this->view_type as $key=>$value)
        {
            if(in_array($content['fstlvlid'], $value))
            {
                $view_type = $key;
                break;
            }
        }

        //导演信息
        $director='';
        $directornew='';
        if(is_array($content['directors']) && !empty($content['directors']))
        {
            if(array_key_exists('key',$content['directors']['director']))
            {
                $director = $content['directors']['director']['value'];
                $directornew = $content['directors']['director']['value'].'|'.$content['directors']['director']['key'];
            }
            else
            {
                foreach ($content['directors']['director'] as $key=>$value)
                {

                    $director.=$value['value'].',';
                    $directornew.=$value['value'].'|'.$value['key'].';';
                }
                $director=rtrim($director, ",");
                $directornew=rtrim($directornew, ";");
            }
        }
        else
        {
            $director = $content['director'];
        }
        //演员信息
        $leader='';
        $leadernew='';
        if(is_array($content['leaders']))
        {
            if(array_key_exists('key',$content['leaders']['leader']))
            {
                $leader = $content['leaders']['leader']['value'];
                $leadernew = $content['leaders']['leader']['value'].'|'.$content['leaders']['leader']['key'];
            }
            else
            {
                foreach ($content['leaders']['leader'] as $key=>$value)
                {
                    $leader.=$value['value'].',';
                    $leadernew.=$value['value'].'|'.$value['key'].';';
                }
                $leader=rtrim($leader, ",");
                $leadernew=rtrim($leadernew, ";");
            }
        }
        else
        {
            $leader = $content['leader'];
        }
        $adaptor='';
        $adaptornew='';
        if(is_array($content['adaptors']))
        {
            if(array_key_exists('key',$content['adaptors']['adaptor']))
            {
                $adaptor = $content['adaptors']['adaptor']['value'];
                $adaptornew = $content['adaptors']['adaptor']['value'].'|'.$content['adaptors']['adaptor']['key'];
            }
            else
            {
                foreach ($content['adaptors']['adaptor'] as $key=>$value)
                {
                    $adaptor.=$value['value'].',';
                    $adaptornew.=$value['value'].'|'.$value['key'].';';
                }
                $adaptor=rtrim($adaptor, ",");
                $adaptornew=rtrim($adaptornew, ";");
            }
        }
        else
        {
            $adaptor = $content['adaptor'];
        }
        //若simplespell为多个多音
        if(!empty($content['simplespell']))
        {
            $simplespell = $content['simplespell'];
            if(strstr($simplespell,'|'))
            {
                $pinying = explode('|', $content['simplespell']);
                $simplespell = $pinying[0];
            }
        }
        else
        {
            $simplespell = m_pinyin::get_pinyin_letter($content['clipname']);
        }
        //海报信息
        $temp_image=array();
        $image = $content['images']['image'];
        if (is_array($image) && !empty($image))
        {
            if (array_key_exists('1', $image))
            {
                foreach ($image as $value)
                {
                    if(array_key_exists($value['imgtype'], $temp_image))
                    {
                        continue;
                    }
                    // 1-横图 2-竖图、小图 3-方图
                    $temp_image[$value['imgtype']] = $value['filename'];
                }
            }
            elseif (array_key_exists('filename', $image))
            {
                $temp_image[$image['imgtype']] = $image['filename'];
            }
        }

        $query_params = array(
            'base_info' => array(
                'nns_asset_import_id' => $content['originalid'],
                'nns_cp_id' => $this->source_id,
                'nns_import_source' => evn::get("project"),
            ),
        );
        $exist_data = $this->vod_action('query', $query_params);

        if ($exist_data['ret'] !=0 || !is_array($exist_data['data_info']) || count($exist_data['data_info']) < 1)
        {
            return \m_config::return_data(1, "查询数据失败或者平台数据不存在");
        }

        //EPG注入数据数组
        $epg_import_arr = array(
            "assets_id" => $content['originalid'],
            "video_type" => 0,
            "assets_category" => (isset($content['fstname']) && strlen($content['fstname']) >0) ? $content['fstname'] : '电影',
            "view_type" => $view_type,
            "name" => $content['clipname'],
            "sreach_key" => $content['keyword'],
            "director" => $director,
            "player" => $leader,
            "user_score_arg" => floatval($content['scores']),//评分
            "tag" => $content['kind'],
            "Tags" => '26,',
            "region" => $content['area'],
            "release_time" => $content['relasetime'],
            "smallpic" => isset($temp_image[2]) ? $temp_image[2] : '',
            "verticality_img" => isset($temp_image[2]) ? $temp_image[2] : '',
            "horizontal_img" => isset($temp_image[1]) ? $temp_image[1] : '',
            "square_img" => isset($temp_image[3]) ? $temp_image[3] : '',
            "intro" => $content['story'],
            "producer" => isset($data['info']['contentprovider']) ? $data['info']['contentprovider'] : '',
            "subordinate_name" => isset($content['othernme']) ? $content['othernme'] : '',
            "language" => $content['language'],
            "view_len" => $content['duration'],
            "original_id" => $content['originalid'],
            'year' => $content['year'],
            'directornew' => $directornew,
            'playernew' => $leadernew,
            'adaptornew' => $adaptornew,
            'isintact' => isset($content['ishuaxu']) ? (int)$content['ishuaxu'] : 0,
            'cp_id' => $this->source_id,
        );
        \m_config::write_message_execute_log('封装后的EPG注入数据数组为' . var_export($epg_import_arr, true), $this->source_id);
        $xml = $this->make_import_xml(array('video' => $epg_import_arr));
        \m_config::write_message_execute_log('封装后的EPG注入数据xml为' . $xml, $this->source_id);
        //注入EPG的参数数组
        $data = array(
            "func" => "modify_video",
            "assets_video_type" => 0,
            "assets_video_info" => $xml,
            "id" => $content['originalid'],
            "bk_message_id" => $this->msg_id,
        );
        \m_config::write_message_execute_log('封装后的注入EPG的参数数组为' . var_export($data, true), $this->source_id);
        //pass_content内容信息转化为json数据格式
        $json_data = json_encode($data);
        //组装pass_queue需要的参数
        $add_pass_queue = array(
            "base_info"=>array(
                "nns_action"=>$data['assetoperation'],
                "nns_type"=>102,
                "nns_message_id"=>$this->msg_id,
                "nns_cp_id"=>$this->source_id,
                "nns_status"=>1,
                "nns_content"=> $json_data,
            )
        );
        $re = $this->pass_queue_action('add', $add_pass_queue);
        return $re;
    }

    /**
     * 分集队列注入
     * @param $data
     * @return array|multitype
     */
    private function index_execute($data)
    {
        $content = $data['content'];
        if ($data['assetoperation'] != 1)
        {
            return \m_config::return_data(1, '只接收处理集合或者分集的修改');
        }

        $clip_index = (intval($content['serialno']) >= 1) ? intval($content['serialno']) : 1;
        if(empty($content['awards']) || !isset($content['awards']))
        {
            $content['awards'] = $content['story'];
        }
        //导演信息
        $director='';
        $directornew='';
        if(is_array($content['directors']) && !empty($content['directors']))
        {
            if(array_key_exists('key',$content['directors']['director']))
            {
                $director = $content['directors']['director']['value'];
                $directornew = $content['directors']['director']['value'].'|'.$content['directors']['director']['key'];
            }
            else
            {
                foreach ($content['directors']['director'] as $key=>$value)
                {

                    $director.=$value['value'].',';
                    $directornew.=$value['value'].'|'.$value['key'].';';
                }
                $director=rtrim($director, ",");
                $directornew=rtrim($directornew, ";");
            }
        }
        else
        {
            $director = $content['director'];
        }
        //演员信息
        $leader='';
        $leadernew='';
        if(is_array($content['leaders']))
        {
            if(array_key_exists('key',$content['leaders']['leader']))
            {
                $leader = $content['leaders']['leader']['value'];
                $leadernew = $content['leaders']['leader']['value'].'|'.$content['leaders']['leader']['key'];
            }
            else
            {
                foreach ($content['leaders']['leader'] as $key=>$value)
                {
                    $leader.=$value['value'].',';
                    $leadernew.=$value['value'].'|'.$value['key'].';';
                }
                $leader=rtrim($leader, ",");
                $leadernew=rtrim($leadernew, ";");
            }
        }
        else
        {
            $leader = $content['leader'];
        }
        //编剧信息
        $adaptor='';
        $adaptornew='';
        if(is_array($content['adaptors']))
        {
            if(array_key_exists('key',$content['adaptors']['adaptor']))
            {
                $adaptor = $content['adaptors']['adaptor']['value'];
                $adaptornew = $content['adaptors']['adaptor']['value'].'|'.$content['adaptors']['adaptor']['key'];
            }
            else
            {
                foreach ($content['adaptors']['adaptor'] as $key=>$value)
                {
                    $adaptor.=$value['value'].',';
                    $adaptornew.=$value['value'].'|'.$value['key'].';';
                }
                $adaptor=rtrim($adaptor, ",");
                $adaptornew=rtrim($adaptornew, ";");
            }
        }
        else
        {
            $adaptor = $content['adaptor'];
        }

        $query_params = array(
            'base_info' => array(
                'nns_import_id' => $content['originalid'],
                'nns_cp_id' => $this->source_id,
                'nns_import_source' => evn::get("project"),
            ),
        );
        $exist_data = $this->index_action('query', $query_params);

        if ($exist_data['ret'] !=0 || !is_array($exist_data['data_info']) || count($exist_data['data_info']) < 1)
        {
            return \m_config::return_data(1, "查询数据失败或者平台数据不存在");
        }
        //EPG注入数据数组
        $epg_import_arr = array(
            'clip_id' => $content['originalid'],
            'name' => $content['partname'],
            'time_len' => $content['duration'],
            'summary' => $content['story'],
            'watch_focus' => addslashes($content['awards']),
            'pic' => $content['images']['image']['filename'],
            'director' => $director,
            'player' => $leader,
            'release_time' => $content['relasetime'],
            'update_time' => $content['updatetime'],
            'original_id' => $content['originalid'],
            'isintact' => $content['isintact'],
            'directornew' => $directornew,
            'playernew' => $leadernew,
            'adaptornew' => $adaptornew,
            'cp_id' => $this->source_id,
        );
        \m_config::write_message_execute_log('封装后的EPG注入数据数组为' . var_export($epg_import_arr, true), $this->source_id);
        $xml = $this->make_import_xml(array('index' => $epg_import_arr));
        \m_config::write_message_execute_log('封装后的EPG注入数据xml为' . $xml, $this->source_id);
        //注入EPG的参数数组
        $data = array(
            "func" => "import_video_clip",
            "assets_id" => $content['oriassetid'],
            "assets_video_type" => 0,
            "id" => $content['originalid'],
            "assets_clip_info" => $xml,
        );
        \m_config::write_message_execute_log('封装后的EPG注入参数数组为' . var_export($data, true), $this->source_id);
        //pass_content内容信息转化为json数据格式
        $json_data = json_encode($data);

        //组装pass_queue需要的参数
        $add_pass_queue = array(
            "base_info"=>array(
                "nns_action"=>$data['assetoperation'],
                "nns_type"=>103,
                "nns_message_id"=>$this->msg_id,
                "nns_cp_id"=>$this->source_id,
                "nns_status"=>1,
                "nns_content"=> $json_data,
            )
        );
        $re = $this->pass_queue_action('add', $add_pass_queue);
        return $re;
    }

    /**
     * 组装XML数据
     * @param array $info 组装XML的数组
     * array(
     *      key => array(value),
     *      key => array(value),
     * )
     * @return string | xml
     */
    public function make_import_xml($info)
    {
        if(!is_array($info) || empty($info))
        {
            return '';
        }
        $dom = new \DOMDocument('1.0', 'utf-8');
        foreach ($info as $key=>$in_value)
        {
            $$key = $dom->createElement($key);
            $dom->appendchild($$key);
            if(!empty($in_value) && is_array($in_value))
            {
                foreach ($in_value as $k=>$val)
                {
                    $$key->setAttribute($k,$val);
                }
            }
        }
        return $dom->saveXML();
    }

    public function status($message_id)
    {

    }

    /**
     * @description:播控注入cdn后统一反馈给二级
     * @author:xinxin.deng
     * @date: 2018/3/2 9:59
     * @param $message_id //消息id
     * @param $code //状态码，失败1，成功0
     * @param $reason //原因描述
     * @param $arr_data //封装好了的反馈信息 array(
     *                                          'cdn_id' => ,注入cdn的id
     *                                          'site_id' => ,配置的站点id
     *                                          'mg_asset_type' => ,注入媒资类型
     *                                          'mg_asset_id' => ,主媒资的消息注入id
     *                                          'mg_part_id' => ,分集的消息注入id
     *                                          'mg_file_id' => ,片源的消息注入id,
     *                                          'is_finally' =>0, 0表示最终状态,反馈的时候将其unset掉
     *                                          );
     * @param $sp_id //sp配置信息
     */
    public function is_ok($message_id, $code, $reason, $arr_data, $sp_id)
    {
        $arr_sp_data = \m_config::_get_sp_info($sp_id);
        $sp_config = isset($arr_sp_data['data_info']['nns_config']) ? $arr_sp_data['data_info']['nns_config'] : array();
        unset($arr_data['is_finally']);
        //兼容湖南电信二级消息反馈，1表示成功，0表示失败。
        $code = $code === 0 ? 1 : 0;
        $flag_message_feedback_enabled = (!isset($sp_config['message_feedback_enabled']) || $sp_config['message_feedback_enabled'] !=1) ? true : false;
        if(!$flag_message_feedback_enabled || !isset($sp_config['message_feedback_mode']) || $sp_config['message_feedback_mode'] != 0)
        {
            \m_config::write_callback_log('[' . date('Y-m-d H:i:s') . ']' . '不允许反馈或者反馈模式不正确：
            [message_feedback_enabled]=' . $sp_config['message_feedback_enabled'] . 'message_feedback_mode=' . $sp_config['message_feedback_mode'], $this->source_id, $message_id);
            return;
        }
        unset($arr_data['is_finally']);//0标识未最终状态
        //查询sp的上报地址/芒果使用站点ID
        if(isset($sp_config['site_id']) && strlen($sp_config['site_id']) > 0 &&
            isset($sp_config['site_callback_url']) && strlen($sp_config['site_callback_url']) > 0)
        {
            $xml_info = array(
                'msgid' => $message_id,
                'state' => $code,
                'msg' => $reason,
                'info' => $arr_data,
            );


            $xml = self::_build_notify_xml($xml_info);
            $data = array(
                'cmsresult' => $xml,
            );
            \m_config::write_callback_log('[' . date('Y-m-d H:i:s') . ']' . '站点反馈地址为:' . var_export($sp_config['site_callback_url'], true) . ',反馈
            数据为:' . $data, $this->source_id, $message_id);

            $http_curl = new np_http_curl_class();
            for ($i = 0; $i < 3; $i++) {
                //访问媒资注入接口
                $re = $http_curl->post($sp_config['site_callback_url'], $data, null, 2);
                $curl_info = $http_curl->curl_getinfo();
                $http_code = $curl_info['http_code'];
                \m_config::write_callback_log('[' . date('Y-m-d H:i:s') . ']' . '循环请求第' . $i . '次(如果请求返回post结果为true并且状态码不是200,就会默认循环3次,状态码为200,
                就跳出循环),' . '请求返回post结果为:' . $re . '请求返回状态为:' . var_export($http_code, true) . ',反回数据为:' . var_export($curl_info, true) . ',
                访问POST结果为:' . var_export($re, true), $this->source_id, $message_id);

                if ($http_code != 200 && (int)$re === 1)
                {
                    continue;
                }
                else
                {
                    break;
                }
            }
        }
        return;
    }


    /**
     * @description:组装反馈的XML
     * @author:xinxin.deng
     * @date: 2018/2/26 14:25
     * @param $params
     * @return string|void
     */
    public function _build_notify_xml($params)
    {
        if(!is_array($params) || empty($params))
        {
            return ;
        }
        $dom = new DOMDocument('1.0', 'utf-8');
        $xmlresult = $dom->createElement('xmlresult');
        $dom->appendChild($xmlresult);
        foreach ($params as $key=>$value)
        {
            $$key = $dom->createElement($key);
            $xmlresult->appendchild($$key);
            if(!empty($value) && is_array($value))
            {
                foreach ($value as $k=>$val)
                {
                    $$k = $dom->createElement($k);
                    $$key->appendchild($$k);
                    //创建元素值
                    $content = $dom->createTextNode($val);
                    $$k->appendchild($content);
                }
            }
            else
            {
                //创建元素值
                $text = $dom->createTextNode($value);
                $$key->appendchild($text);
            }
        }
        return $dom->saveXML();
    }


    /**
     * 消息队列注入播控统一反馈给芒果二级，组装消息结构
     * @param int $state
     * @param string $reason
     * @param array $info
     */
    public function create_xml_respond_msg_to_csp($state=0, $reason='',$info=array())
    {

        $site_id = $this->arr_cp_config['data_info']['nns_config']['site_id'];
        $site_url = $this->arr_cp_config['data_info']['nns_config']['site_callback_url'];

        \m_config::write_callback_log('反馈到芒果二级地址信息：站点为-' . $site_id . ';站点地址为-' . $site_url, $this->source_id, $this->msg_id);
        //反馈状态转换
        $state = $state== 0 ?  1 : 0;
        if(!empty($site_id) && !empty($site_url))
        {
            $params = array(
                'msgid' => $this->msg_id,
                'state' => $state,
                'msg' => $reason
            );
            if(!empty($info))
            {
                $params['info'] = $info;
            }
            else
            {
                $params['info'] = array(
                    'cdn_id' => '',
                    'site_id' => $site_id,
                    'mg_asset_type' => $this->type,
                    'mg_asset_id' => $this->asset_id,
                    'mg_part_id' => $this->index_id,
                    'mg_file_id' => $this->media_id,
                );
            }
            $this->notify_msg($params, true, $site_url);
        }
        else
        {
            \m_config::write_callback_log('没有配置站点信息', $this->source_id, $this->msg_id);
        }
    }

    /**
     * 进行消息反馈
     * @param $params
     * @param bool $bool
     * @param string $site_url
     * @return array|string|void
     */
    public function notify_msg($params, $bool=false, $site_url='')
    {
        $http_curl = new np_http_curl_class();
        $xml = $this->_build_notify_xml($params);
        \m_config::write_callback_log('反馈给芒果二级的数据为：' . var_export($xml,true), $this->source_id, $this->msg_id);

        if(!$bool)//是否异步反馈通知上游
        {
            return $xml;
        }
        if(!empty($site_url))
        {
            $xml = array('cmsresult '=> $xml);
            $response = $http_curl->post($site_url, $xml, null, 2);
            $curl_info = $http_curl->curl_getinfo();
            \m_config::write_callback_log('芒果接收到反馈后响应的结果为：' . $response . ',POST反馈数据为：' . var_export($curl_info,true), $this->source_id, $this->msg_id);
        }
        else
        {
            \m_config::write_callback_log('没有配置反馈地址', $this->source_id, $this->media_id);
        }
    }

}